﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.Configuration;
using System.Web.Security;
using System.Management;

public delegate void SubInvoker(object sInput);
public delegate object FunctionInvoker(object sInput);
public delegate void FormatInvoker(string sFieldName, ref object sValue);

public partial class Globals
{
    public const string vbCr = "\r";
    public const string vbLf = "\n";
    public const string vbCrLf = "\r\n"; //System.NewLine
    public const string vbTab = "\t";

    public static string Application_GetConfig(string sSectionKey, bool bEncode)
    {
        string sValue = Application_GetConfig(sSectionKey);
        if (bEncode)
        {
            Assembly m_MyAssembly = Assembly.GetCallingAssembly();
            string sGUID = m_MyAssembly.GetType().GUID.ToString();
            sValue = String_Decrypt(sValue, Application_GetID(sGUID));
        }
        return sValue;
    }

    public static string Application_GetConfig(string sSectionKey)
    {
        string sValue = ConfigurationManager.AppSettings[sSectionKey];
        return sValue;
    }

    public static void Application_SetConfig(string sSectionKey, string sValue, bool bEncode)
    {
        if (bEncode)
        {
            Assembly m_MyAssembly = Assembly.GetCallingAssembly();
            string sGUID = m_MyAssembly.GetType().GUID.ToString();
            sValue = String_Encrypt(sValue, Application_GetID(sGUID));
        }
        Application_SetConfig(sSectionKey, sValue);
    }

    public static void Application_SetConfig(string sSectionKey, string sValue)
    {
        System.Configuration.Configuration config = default(System.Configuration.Configuration);
        if (System.Web.HttpRuntime.AppDomainAppId == null)
        {
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        }
        else
        {
            config = WebConfigurationManager.OpenWebConfiguration("~");
        }
        // Add an Application Setting.
        if (Array.IndexOf(config.AppSettings.Settings.AllKeys, sSectionKey) >= 0)
        {
            config.AppSettings.Settings[sSectionKey].Value = sValue;
        }
        else
        {
            config.AppSettings.Settings.Add(sSectionKey, sValue);
        }
        // Save the configuration file.
        config.Save(ConfigurationSaveMode.Modified);
        // Force a reload of a changed section.
        ConfigurationManager.RefreshSection("appSettings");
    }

    public static string Application_GetDesc()
    {
        Assembly m_MyAssembly = Assembly.GetEntryAssembly();
        if (m_MyAssembly.IsDefined(typeof(AssemblyDescriptionAttribute), true))
        {
            Attribute attr = Attribute.GetCustomAttribute(m_MyAssembly, typeof(AssemblyDescriptionAttribute));
            AssemblyDescriptionAttribute title_attr = (AssemblyDescriptionAttribute)attr;
            return title_attr.Description;
        }
        else
        {
            return "";
        }
    }

    public static string Application_GetTitle()
    {
        Assembly m_MyAssembly = Assembly.GetEntryAssembly();
        if (m_MyAssembly.IsDefined(typeof(AssemblyTitleAttribute), true))
        {
            Attribute attr = Attribute.GetCustomAttribute(m_MyAssembly, typeof(AssemblyTitleAttribute));
            AssemblyTitleAttribute title_attr = (AssemblyTitleAttribute)attr;
            return title_attr.Title;
        }
        else
        {
            return "";
        }
    }

    public static string Application_GetVersion()
    {
        Assembly m_MyAssembly = Assembly.GetEntryAssembly();
        FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(m_MyAssembly.Location);
        return fvi.FileVersion;
    }

    public static string Application_GetPath()
    {
        Assembly m_MyAssembly = Assembly.GetEntryAssembly();
        string sPath = m_MyAssembly.Location;
        return sPath.Substring(0, sPath.LastIndexOf("\\"));
    }

    private static string Application_GetID(string sGUID)
    {
        //Dim sGUID As String = m_MyAssembly.GetType().GUID.ToString()
        decimal retVal = 0;
        foreach (string sHex in sGUID.Split('-'))
        {
            retVal += long.Parse(sHex, System.Globalization.NumberStyles.HexNumber);
        }
        return retVal.ToString();
    }

    public static string Application_GetID()
    {
        Assembly m_MyAssembly = Assembly.GetEntryAssembly();
        string sGUID = m_MyAssembly.GetType().GUID.ToString();
        return Application_GetID(sGUID);
    }

    public static void Application_SetCultureInfo(System.Threading.Thread mThread)
    {
        //Set khuôn dạng Date và Number cho 1 thread
        System.Globalization.DateTimeFormatInfo myDateformat = new System.Globalization.DateTimeFormatInfo();
        myDateformat.ShortDatePattern = CS_DISPLAY_DATE_FORMAT;
        myDateformat.DateSeparator = CS_DATETIME_SYMBOL;
        myDateformat.FullDateTimePattern = CS_DISPLAY_DATETIME_FORMAT;
        //Set upper case for abb month name
        string[] arrMonthName = myDateformat.AbbreviatedMonthNames;
        arrMonthName.Clone();
        for (int i = 0; i <= arrMonthName.Length - 1; i++)
        {
            arrMonthName[i] = arrMonthName[i].ToUpper();
        }
        myDateformat.AbbreviatedMonthNames = arrMonthName;
        //
        System.Globalization.NumberFormatInfo myNumberformat = new System.Globalization.NumberFormatInfo();
        myNumberformat.NumberDecimalSeparator = CS_DECIMAL_SYMBOL;
        myNumberformat.CurrencyDecimalSeparator = myNumberformat.NumberDecimalSeparator;
        myNumberformat.NumberGroupSeparator = CS_DIGIT_GROUP_SYMBOL;
        myNumberformat.CurrencyGroupSeparator = myNumberformat.NumberGroupSeparator;
        //
        mThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
        mThread.CurrentCulture.DateTimeFormat = myDateformat;
        mThread.CurrentCulture.NumberFormat = myNumberformat;
    }

    public static string GetConnectionSetting(string sSectionKey)
    {
        string sValue = ConfigurationManager.ConnectionStrings[sSectionKey].ConnectionString;
        return sValue;
    }

    public static string ArrayToString(object[] arrObject)
    {
        return ArrayToString(arrObject, ",");
    }

    public static string ArrayToString(object[] arrObject, string seperator)
    {
        string retVal = "";
        foreach (object obj in arrObject)
        {
            if (retVal.Length > 0)
                retVal += seperator;
            retVal += obj.ToString();
        }
        return retVal;
    }

    public static object DB_GetNull(object objField)
    {
        return Null.GetNull(objField, DBNull.Value);
    }

    public static object DB_GetNull(object objField, object objNull)
    {
        return Null.GetNull(objField, objNull);
    }

    public static object DB_GetValue(object objField, object objDefault)
    {
        if (object.ReferenceEquals(objField, DBNull.Value) || objField == null)
        {
            return objDefault;
        }
        else
        {
            return objField;
        }
    }

    public static T DB_GetValue<T>(object objField, T objDefault)
    {
        if (object.ReferenceEquals(objField, DBNull.Value) || objField == null)
        {
            return objDefault;
        }
        else
        {
            return (T)objField;
        }
    }

    public static T DB_GetValue<T>(object objField)
    {
        return (T)Null.GetNull(objField, Null.GetNullOfType<T>());
    }

    public static bool DB_CheckValue(object objField)
    {
        if (object.ReferenceEquals(objField, DBNull.Value) || objField == null)
        {
            return false;
        }
        else
        {
            if (objField is string)
            {
                return !string.IsNullOrEmpty(objField.ToString());
            }
            else
            {
                return true;
            }
        }
    }

    public static string DB_GetString(object objField)
    {
        return DB_GetString(objField, "");
    }

    public static string DB_GetString(object objField, string strDefault)
    {
        if (object.ReferenceEquals(objField, DBNull.Value) || objField == null)
        {
            return strDefault;
        }
        else
        {
            if (objField is System.DateTime)
            {
                return ((System.DateTime)objField).ToString(CS_DISPLAY_DATE_FORMAT);
            }
            else if ((objField != null))
            {
                if (objField.GetType().IsValueType && !(objField is bool))
                {
                    return String.Format(objField.ToString(), "##0.##");
                }
                else
                {
                    return objField.ToString();
                }
            }
            else
            {
                return "";
            }
        }
    }

    public static string String_Repeat(string sChar, int iCount)
    {
        //Lap lai ky tu n lan
        string sReturn = "";
        if (sChar.Length == 1)
        {
            sReturn = sReturn.PadRight(iCount, sChar[0]);
        }
        else
        {
            for (int i = 1; i <= iCount; i++)
            {
                sReturn += sChar;
            }
        }
        return sReturn;
    }

    public static bool String_IsAlphaNumeric(string sText)
    {
        //Ham kiem tra chuoi co bao gom ca chu va so hay khong
        //thuong dung de kiem tra khi khoi tao mat khau
        return Regex.IsMatch(sText, "^(?=.*\\d)(?=.*[a-zA-Z])");
    }

    public static string String_StripDiacritics(string sText)
    {
        //Lay chuoi ky tu khong dau
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\p{IsCombiningDiacriticalMarks}+");
        //
        string strFormD = sText.Normalize(System.Text.NormalizationForm.FormD);
        return regex.Replace(strFormD, string.Empty).Replace((char)(0x111), 'd').Replace((char)(0x110), 'D').Replace((char)(0xd0), 'D');
    }

    public static string String_Number(decimal numValue)
    {
        string sDecChar = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
        string retVal = numValue.ToString();
        retVal = retVal.Replace(sDecChar, ".");
        return retVal;
    }

    public static string String_ClearInjection(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return "";
        }
        else if (input.Contains(";") && (input.Contains("--") || input.Contains("/*") || input.ToUpper().Contains("DECLARE")))
        {
            return "";
        }
        else
        {
            return input.Replace("'", "''");
        }
    }

    public static void String_ConditionAppend(ref string condition, string input)
    {
        String_ConditionAppend(ref condition, input, "AND");
    }

    public static void String_ConditionAppend(ref string condition, string input, string sConnector)
    {
        if (string.IsNullOrEmpty(input))
            return;
        input = input.Trim();
        if (!input.StartsWith("("))
            input = "(" + input + ")";
        if (string.IsNullOrEmpty(condition))
        {
            condition = input;
        }
        else
        {
            condition += " " + sConnector + " " + input;
        }
    }

    public static string String_ParseFullText(string searchText, bool bMatchAll)
    {
        if (string.IsNullOrEmpty(searchText))
            return "";
        System.Collections.Generic.List<string> lstKeyword = String_ParseKeywords(searchText);
        string sTemp = "";
        if ((lstKeyword != null))
        {
            string sw = "";
            foreach (string sWord in lstKeyword)
            {
                if (sWord.Contains(" "))
                    sw = "\"" + sWord + "\"";
                else
                    sw = sWord;

                if (sTemp.Length == 0)
                {
                    sTemp = sw;
                }
                else
                {
                    if (bMatchAll)
                    {
                        sTemp += " AND " + sw;
                    }
                    else
                    {
                        sTemp += " OR " + sw;
                    }
                }
            }
        }
        return sTemp;
    }

    public static string String_ParseLike(string fieldName, string searchText, bool bMatchAll)
    {
        List<string> lstKeyword = String_ParseKeywords(searchText);
        string retVal = "";
        string sWord = "";
        if ((lstKeyword != null))
        {
            foreach (string sTemp in lstKeyword)
            {
                sWord = sTemp.Trim();
                if (sWord.Contains("*"))
                {
                    sWord = sWord.Replace("*", "%");
                }
                if (retVal.Length > 0)
                {
                    if (bMatchAll)
                    {
                        retVal += " AND ";
                    }
                    else
                    {
                        retVal += " OR ";
                    }
                }
                retVal += "(";
                retVal += fieldName + " LIKE N'% " + sWord + " %'";
                retVal += " OR ";
                retVal += fieldName + " LIKE N'" + sWord + " %'";
                retVal += " OR ";
                retVal += fieldName + " LIKE N'% " + sWord + "'";
                retVal += " OR ";
                retVal += fieldName + " = N'" + sWord + "'";
                retVal += ")";
            }
        }
        return retVal;
    }

    public static string String_ParseLikeEx(string fieldName, string searchText, bool bMatchAll)
    {
        List<string> lstKeyword = String_ParseKeywords(searchText);
        string retVal = "";
        string sWord = "";
        if ((lstKeyword != null))
        {
            fieldName = "LOWER(" + fieldName + ")";
            foreach (string sTemp in lstKeyword)
            {
                sWord = sTemp.Trim().ToLower();
                if (sWord.Contains("*"))
                {
                    sWord = sWord.Replace("*", "%");
                }
                if (retVal.Length > 0)
                {
                    if (bMatchAll)
                    {
                        retVal += " AND ";
                    }
                    else
                    {
                        retVal += " OR ";
                    }
                }
                retVal += "(";
                retVal += fieldName + " LIKE N'% " + sWord + " %'";
                retVal += " OR ";
                retVal += fieldName + " LIKE N'" + sWord + " %'";
                retVal += " OR ";
                retVal += fieldName + " LIKE N'% " + sWord + "'";
                retVal += " OR ";
                retVal += fieldName + " = N'" + sWord + "'";
                retVal += ")";
            }
        }
        return retVal;
    }

    public static List<string> String_ParseKeywords(string sText)
    {
        if (string.IsNullOrEmpty(sText))
        {
            return null;
        }
        sText = sText.Trim();
        sText = sText.Replace(",", "");
        sText = sText.Replace(".", "");
        List<string> lstKeyword = new List<string>();
        int iPos = sText.IndexOf("\"");
        string sKeyword = null;
        if (iPos == -1)
        {
            lstKeyword.AddRange(sText.Split(' '));
        }
        else
        {
            while (iPos > -1)
            {
                if (iPos > 0)
                {
                    sKeyword = sText.Substring(0, iPos).Trim();
                    lstKeyword.AddRange(sKeyword.Split(' '));
                    sText = sText.Substring(iPos).Trim();
                }
                else
                {
                    iPos = sText.IndexOf("\"", iPos + 1);
                    if (iPos > 0)
                    {
                        sKeyword = sText.Substring(1, iPos - 1);
                        lstKeyword.Add(sKeyword);
                        if (iPos + 1 == sText.Length)
                        {
                            break; // TODO: might not be correct. Was : Exit Do
                        }
                        sText = sText.Substring(iPos + 1).Trim();
                    }
                    else
                    {
                        break; // TODO: might not be correct. Was : Exit Do
                    }
                }
                iPos = sText.IndexOf("\"");
                if (iPos == -1)
                {
                    lstKeyword.AddRange(sText.Split(' '));
                    break; // TODO: might not be correct. Was : Exit Do
                }
            }
        }
        return lstKeyword;
    }

    public static string String_IsValidEmail(string emailList, string emailSep)
    {
        string retVal = "";
        //foreach (object emailAddress_loopVariable in emailList.Split(emailSep))
        //{
        //    emailAddress = emailAddress_loopVariable;
        //    if (!String_IsValidEmail(emailAddress))
        //    {
        //        if (retVal.Length > 0)
        //            retVal += emailSep;
        //        retVal += emailAddress;
        //    }
        //}
        return retVal;
    }

    /// <summary>
    /// method for determining is the user provided a valid email address
    /// We use regular expressions in this check, as it is a more thorough
    /// way of checking the address provided
    /// </summary>
    /// <param name="email">email address to validate</param>
    /// <returns>true is valid, false if not valid</returns>
    public static bool String_IsValidEmail(string email)
    {
        //regular expression pattern for valid email
        //addresses, allows for the following domains:
        //com,edu,info,gov,int,mil,net,org,biz,name,museum,coop,aero,pro,tv
        string pattern = "[a-zA-Z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*@[-.a-zA-Z0-9]+(\\.[-.a-zA-Z0-9]+)*\\." + "(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$";
        //Dim pattern As String = "^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\." & _
        //"(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$"
        //Regular expression object
        System.Text.RegularExpressions.Regex check = new System.Text.RegularExpressions.Regex(pattern, RegexOptions.IgnorePatternWhitespace & RegexOptions.IgnoreCase);
        //boolean variable to return to calling method
        bool valid = false;

        //make sure an email address was provided
        if (string.IsNullOrEmpty(email))
        {
            valid = false;
        }
        else
        {
            //use IsMatch to validate the address
            valid = check.IsMatch(email);
        }
        //return the value to the calling method
        return valid;
    }

    public static bool String_IsValidWeb(string address)
    {
        return Regex.IsMatch(address, "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
    }

    public static string String_Reverse(string input)
    {
        if (string.IsNullOrEmpty(input))
            throw new ArgumentNullException("input");
        char[] charArray = input.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }

    public static string String_Encrypt(string strText, string strEncrKey)
    {
        try
        {
            strEncrKey = (strEncrKey + String_Repeat("0", IV.Length)).Substring(0, IV.Length);
            byte[] bykey = System.Text.Encoding.UTF8.GetBytes(strEncrKey);
            byte[] InputByteArray = System.Text.Encoding.UTF8.GetBytes(strText);
            RijndaelManaged des = new RijndaelManaged();
            des.KeySize = IV.Length * 8;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(bykey, IV), CryptoStreamMode.Write);

            cs.Write(InputByteArray, 0, InputByteArray.Length);
            cs.FlushFinalBlock();

            string retVal = Convert.ToBase64String(ms.ToArray());
            return retVal;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    public static byte[] ByteArray_Encrypt(byte[] InputByteArray, string strEncrKey)
    {
        try
        {
            strEncrKey = (strEncrKey + String_Repeat("0", IV.Length)).Substring(0, IV.Length);
            byte[] bykey = System.Text.Encoding.UTF8.GetBytes(strEncrKey);
            RijndaelManaged des = new RijndaelManaged();
            des.KeySize = IV.Length * 8;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(bykey, IV), CryptoStreamMode.Write);

            cs.Write(InputByteArray, 0, InputByteArray.Length);
            cs.FlushFinalBlock();

            return ms.ToArray();
        }
        catch
        {
            return null;
        }
    }

    public static string String_Decrypt(string strText, string sDecrKey)
    {
        byte[] inputByteArray = new byte[strText.Length + 1];
        try
        {
            sDecrKey = (sDecrKey + String_Repeat("0", IV.Length)).Substring(0, IV.Length);
            byte[] byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey);
            RijndaelManaged des = new RijndaelManaged();
            des.KeySize = IV.Length * 8;
            inputByteArray = Convert.FromBase64String(strText);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

            return encoding.GetString(ms.ToArray());
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    public byte[] ByteArray_Decrypt(byte[] inputByteArray, string sDecrKey)
    {
        try
        {
            sDecrKey = (sDecrKey + String_Repeat("0", IV.Length)).Substring(0, IV.Length);
            byte[] byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey);
            RijndaelManaged des = new RijndaelManaged();
            des.KeySize = IV.Length * 8;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            return ms.ToArray();
        }
        catch
        {
            return null;
        }
    }

    //Public Function RSA_Encrypt(ByVal DataToEncrypt() As Byte) As Byte()
    //    Try
    //        RSA_ValidateKeys()
    //        '
    //        Dim encryptedData() As Byte
    //        Using RSA As New RSACryptoServiceProvider(2048)               
    //            RSA.FromXmlString(IO.File.ReadAllText(RSA_KEY_PUBLIC))
    //            encryptedData = RSA.Encrypt(DataToEncrypt, True)
    //        End Using
    //        Return encryptedData
    //        'Catch and display a CryptographicException   
    //        'to the console. 
    //    Catch e As CryptographicException
    //        Return Nothing
    //    End Try
    //End Function

    //Private RSA_KEY_PUBLIC As String = "Lib\public.key"
    //Private RSA_KEY_PRIVATE As String = "Lib\private.key"
    //Private Sub RSA_ValidateKeys()
    //    If Not Web.HttpRuntime.AppDomainAppId Is Nothing AndAlso Not RSA_KEY_PRIVATE.Contains(Web.HttpRuntime.AppDomainAppPath) Then
    //        RSA_KEY_PRIVATE = Web.HttpRuntime.AppDomainAppPath + "bin\" + RSA_KEY_PRIVATE
    //        RSA_KEY_PUBLIC = Web.HttpRuntime.AppDomainAppPath + "bin\" + RSA_KEY_PUBLIC
    //    End If
    //    If Not File.Exists(RSA_KEY_PRIVATE) AndAlso Not File.Exists(RSA_KEY_PUBLIC) Then
    //        Dim key As RSA = RSA.Create
    //        key.KeySize = 2048
    //        Dim privateKey As String = key.ToXmlString(True)
    //        Dim publicKey As String = key.ToXmlString(False)
    //        Dim privateFile As StreamWriter = File.CreateText(RSA_KEY_PRIVATE)
    //        privateFile.Write(privateKey)
    //        privateFile.Close()
    //        privateFile.Dispose()
    //        Dim publicFile As StreamWriter = File.CreateText(RSA_KEY_PUBLIC)
    //        publicFile.Write(publicKey)
    //        publicFile.Close()
    //        publicFile.Dispose()
    //    End If
    //End Sub

    //Public Function RSA_Decrypt(ByVal DataToDecrypt() As Byte) As Byte()
    //    Try
    //        RSA_ValidateKeys()
    //        '
    //        Dim decryptedData() As Byte
    //        'Create a new instance of RSACryptoServiceProvider. 
    //        Using RSA As New RSACryptoServiceProvider(2048)
    //            'Import the RSA Key information. This needs 
    //            'to include the private key information.
    //            RSA.FromXmlString(File.ReadAllText(RSA_KEY_PRIVATE))
    //            'Decrypt the passed byte array and specify OAEP padding.   
    //            'OAEP padding is only available on Microsoft Windows XP or 
    //            'later.  
    //            decryptedData = RSA.Decrypt(DataToDecrypt, True)
    //            'Catch and display a CryptographicException   
    //            'to the console. 
    //        End Using
    //        Return decryptedData
    //    Catch e As CryptographicException
    //        Return Nothing
    //    End Try
    //End Function

    public string String_Hash(string input)
    {
        // Create a new instance of the MD5 object.
        System.Security.Cryptography.MD5 md5Hasher = System.Security.Cryptography.MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        System.Text.StringBuilder sBuilder = new System.Text.StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        int i = 0;
        for (i = 0; i <= data.Length - 1; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }

    public bool String_IsBase64(string sValue)
    {
        return Regex.IsMatch(sValue, "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$");
    }

    public string String_Random(int iLen)
    {
        //Dung cac ky tu chu:
        //   0-9: 48-57 map 0-9
        //   A-Z: 65-90 map 10-35
        //   a-z: 97-122 map 36-61

        string sRet = "";
        string iASCII = "";
        Random r = new Random();

        for (int i = 1; i <= iLen; i++)
        {
            //Lay random 1 so thu tu
            //Chi dung chu hoa nen lay random trong 35
            int iIndex = r.Next(0, 35);
            //Lay ra ascii tuong ung cua ky tu tuong ung voi so thu tu theo map o phan dau
            switch (iIndex)
            {
                case  // ERROR: Case labels with binary operators are unsupported : LessThan
    10:
                    //iIndex = iIndex
                    iIndex += 48;
                    break;
                case  // ERROR: Case labels with binary operators are unsupported : LessThan
    36:
                    iIndex = iIndex + 55;
                    break;
                default:
                    //<62
                    iIndex = iIndex + 61;
                    break;
            }
            //Lay ra ky tu ASCII tuong ung
            sRet += (char)(iIndex);
        }

        r = null;

        return sRet;
    }

    public string String_Date2Text(DateTime dateValue)
    {
        string retVal = null;
        retVal = "Ngày " + (dateValue.Day <= 10 ? "mùng " : "") + String_Num2Text(dateValue.Day.ToString(), false) + ", tháng " + String_Num2Text(dateValue.Month.ToString(), false) + ", năm " + String_Num2Text(dateValue.Year.ToString(), false);
        return retVal;
    }

    public string String_SqlDate(string sValue)
    {
        return String_SqlDate(Object_SetValueEx<System.DateTime>(sValue));
    }

    public string String_SqlDate(System.DateTime dtValue)
    {
        if (dtValue.Year > 1900)
        {
            return "CONVERT(DATETIME,'" + dtValue.ToString("dd/MM/yyyy") + "',103)";
        }
        else
        {
            return "";
        }
    }

    public string String_OracleDate(string sValue)
    {
        return String_OracleDate(Object_SetValueEx<System.DateTime>(sValue));
    }

    public string String_OracleDate(System.DateTime dtValue)
    {
        if (dtValue.Year > 1900)
        {
            return "TO_DATE('" + dtValue.ToString("dd/MM/yyyy") + "','dd/MM/yyyy')";
        }
        else
        {
            return "";
        }
    }

    public static string String_Num2Text(string mNumber, bool bUpcaseFirst)
    {
        if (mNumber.Contains(CS_DECIMAL_SYMBOL))
        {
            mNumber = mNumber.Substring(0, mNumber.IndexOf(CS_DECIMAL_SYMBOL));
        }
        mNumber = mNumber.Replace(CS_DIGIT_GROUP_SYMBOL, "");
        //
        int mLen = 0;
        int i = 0;
        int mDigit = 0;
        string mTemp = null;
        string[] mNumText = null;
        mNumText = new string[] {
		"không",
		"một",
		"hai",
		"ba",
		"bốn",
		"năm",
		"sáu",
		"bảy",
		"tám",
		"chín"
	};
        mLen = mNumber.Length;
        for (i = 1; i <= mLen; i++)
        {
            mDigit = int.Parse(mNumber[i - 1].ToString());
            mTemp += " " + mNumText[mDigit];
            if ((mLen == i))
                break; // TODO: might not be correct. Was : Exit For
            decimal tmp = decimal.Remainder(ToDecimal(mLen - i), ToDecimal(9));
            if (tmp == 0m)
            {
                mTemp += " tỷ";
                if (mNumber.Substring(i, 9) == "000000000")
                    i = i + 9;
                if (i >= mLen)
                    break; // TODO: might not be correct. Was : Exit For

                if (mNumber.Substring(i, 3) == "000")
                    i = i + 2;
                //doc ca truong hop "... ty ... khong trieu ... nghin "
                //break;
                //If mNumber.Substring(i, 3) = "000" Then i = i + 3'bo qua truong hop "khong trieu" 
            }
            else if (tmp == 6m)
            {
                mTemp += " triệu";
                if (mNumber.Substring(i, 6) == "000000")
                    i = i + 6;
                if (i >= mLen)
                    break; // TODO: might not be correct. Was : Exit For

                if (mNumber.Substring(i, 3) == "000")
                    i = i + 2;
                //doc ca truong hop "... trieu ... khong nghin ... "
                //break;
                //If mNumber.Substring(i, 3) = "000" Then i = i + 3'bo qua truong hop "khong nghin" 
            }
            else if (tmp == 3m)
            {
                mTemp += " nghìn";
                if (mNumber.Substring(i, 3) == "000")
                    i = i + 3;
                //break;
            }
            else
            {
                decimal defaulttmp = decimal.Remainder((mLen - i), 3);
                if (defaulttmp == 2m)
                    mTemp += " trăm";
                else if (defaulttmp == 1m)
                    mTemp += " mươi";
                //break;
            }
        }
        //bo 00
        mTemp = mTemp.Replace("không mươi không", "");
        //truong hop 0x
        mTemp = mTemp.Replace("không mươi ", "linh ");
        mTemp = mTemp.Replace("mươi không", "mươi");
        mTemp = mTemp.Replace("một mươi", "mười");
        //x4 (x>1)
        mTemp = mTemp.Replace("mươi bốn", "mươi tư");
        //04
        mTemp = mTemp.Replace("linh bốn", "linh tư");
        //x5 (x>1)
        //mTemp = mTemp.Replace("mươi năm", "mươi nhăm")
        mTemp = mTemp.Replace("mươi năm", "mươi lăm");
        //x1 (x>1)
        mTemp = mTemp.Replace("mươi một", "mươi mốt");
        //15
        mTemp = mTemp.Replace("mười năm", "mười lăm");
        //clear double space
        mTemp = mTemp.Replace("  ", " ");
        mTemp = mTemp.Trim();
        if (mTemp.StartsWith("linh "))
            mTemp = mTemp.Substring("linh ".Length);
        if (bUpcaseFirst)
            mTemp = mTemp.Substring(0, 1).ToUpper() + mTemp.Substring(1);
        return mTemp;
    }

    public static string String_Num2Text(string mNumber)
    {
        return String_Num2Text(mNumber, true);
    }

    public string String_Capitalize(string sText)
    {
        string sTemp = "";
        foreach (string sWord in sText.Split(' '))
        {
            if (sWord.Length > 0)
            {
                if (sTemp.Length > 0)
                    sTemp += " ";
                sTemp += sWord.Substring(0, 1).ToUpper();
                if (sWord.Length > 1)
                    sTemp += sWord.Substring(1).ToLower();
            }
        }
        return sTemp;
    }

    public string String_Abstract(string sText, int iLen, string[] arrBreak)
    {
        if (sText == null)
            return "";
        sText = sText.Trim();
        //sText = sText.Replace(Constants.vbCrLf, " ");
        //sText = sText.Replace(Constants.vbCr, " ");
        if (sText.Length == 0)
            return "";
        if (sText.Length > iLen)
        {
            sText = sText.Substring(0, iLen);
            int iPos = 0;
            int iTemp = 0;
            if ((arrBreak != null))
            {
                foreach (string sBreak in arrBreak)
                {
                    iTemp = sText.LastIndexOf(sBreak);
                    if (iTemp > iPos)
                        iPos = iTemp;
                }
            }
            if (iPos == 0 || iPos < iLen - 10)
                iPos = sText.LastIndexOf(" ");
            if (iPos > 0)
            {
                sText = sText.Substring(0, iPos);
                //+ " ..."
            }
        }
        return sText;
    }

    public string String_Compress(string sUncompress)
    {
        string Result = string.Empty;
        //Convert the uncompressed string into a byte array
        byte[] UnZippedData = System.Text.Encoding.UTF8.GetBytes(sUncompress);
        //Compress the byte array
        byte[] ZippedData = ByteArray_Compress(UnZippedData);
        //Convert the compressed byte array back to a string
        Result = System.Convert.ToBase64String(ZippedData);
        //
        return Result;
    }

    public string String_Decompress(string sCompress)
    {
        string Result = string.Empty;
        byte[] ZippedData = null;
        //Convert the compressed string into a byte array and decrypt the array if required    
        ZippedData = System.Convert.FromBase64String(sCompress);
        //Decompress the byte array
        byte[] UnZippedData = ByteArray_Decompress(ZippedData);
        //Convert the decompressed byte array back to a string
        Result = System.Text.Encoding.UTF8.GetString(UnZippedData);
        //
        return Result;
    }

    public string String_FormatNumber(byte iScale)
    {
        string retVal = "#" + CS_DIGIT_GROUP_SYMBOL + "###";
        if (iScale > 0)
        {
            retVal += CS_DECIMAL_SYMBOL + String_Repeat("#", iScale);
        }
        return retVal;
    }

    public string ByteArray_ToString(byte[] data)
    {
        string retVal = null;
        using (StreamReader r = new StreamReader(new MemoryStream(data), System.Text.Encoding.Default))
        {
            retVal = r.ReadToEnd();
        }
        return retVal;
    }

    public byte[] ByteArray_Compress(byte[] UnZippedData)
    {
        byte[] Result = null;
        //Compress the byte array
        //Result = QuickLZ.compress(UnZippedData, 3);
        return Result;
    }

    public byte[] ByteArray_Decompress(byte[] ZippedData)
    {
        byte[] Result = null;
        //Decompress the byte array
        //Result = QuickLZ.decompress(ZippedData);
        return Result;
    }

    public Stream Stream_Compress(System.IO.Stream input)
    {
        if (input == null)
            return null;
        //
        int streamLength = Convert.ToInt32(input.Length);
        byte[] arrBytes = new byte[streamLength];
        // Read the file into a byte array
        input.Read(arrBytes, 0, streamLength);
        input.Close();
        MemoryStream output = new MemoryStream(ByteArray_Compress(arrBytes));
        //
        return output;
    }

    public Stream Stream_Decompress(System.IO.Stream input)
    {
        if (input == null)
            return null;
        //
        int streamLength = Convert.ToInt32(input.Length);
        byte[] arrBytes = new byte[streamLength];
        // Read the file into a byte array
        input.Read(arrBytes, 0, streamLength);
        input.Close();
        MemoryStream output = new MemoryStream(ByteArray_Decompress(arrBytes));
        //
        return output;
    }

    public static DataTable Reader2Table(IDataReader objDataReader)
    {
        DataTable dt = new DataTable();
        dt.Load(objDataReader);
        objDataReader.Close();
        objDataReader.Dispose();
        return dt;
    }

    public static DataTable DataPager(DataSet objData, ref int iTotal)
    {
        if (objData.Tables.Count > 1)
        {
            if (objData.Tables[0].Columns.Count == 1 && objData.Tables[0].Rows.Count == 1)
            {
                iTotal = DB_GetValue<Int32>(objData.Tables[0].Rows[0][0], 0);
                return objData.Tables[1];
            }
            else if (objData.Tables[1].Columns.Count == 1 && objData.Tables[1].Rows.Count == 1)
            {
                iTotal = DB_GetValue<Int32>(objData.Tables[1].Rows[0][0], 0);
                return objData.Tables[0];
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    public static void DataTable_SetKey(DataTable dt, string sColName)
    {
        dt.PrimaryKey = new DataColumn[] { dt.Columns[sColName] };
        dt.AcceptChanges();
    }

    public static void DataTable_SetUnique(DataTable dt, params string[] arrColName)
    {
        DataColumn[] arrColumn = (DataColumn[])Array.CreateInstance(typeof(DataColumn), arrColName.Length);
        for (int i = 0; i <= arrColName.Length - 1; i++)
        {
            arrColumn[i] = dt.Columns[arrColName[i]];
        }
        UniqueConstraint uc1 = new UniqueConstraint("uc" + string.Join("_", arrColName), arrColumn);
        dt.Constraints.Add(uc1);
        dt.AcceptChanges();
    }

    public static void DataTable_SetNull(DataTable dt, params string[] arrColName)
    {
        for (int i = 0; i <= arrColName.Length - 1; i++)
        {
            dt.Columns[arrColName[i]].AllowDBNull = true;
        }
        dt.AcceptChanges();
    }

    public static void DataTable_SetNotNull(DataTable dt, params string[] arrColName)
    {
        for (int i = 0; i <= arrColName.Length - 1; i++)
        {
            dt.Columns[arrColName[i]].AllowDBNull = false;
        }
        dt.AcceptChanges();
    }

    public void DataTable_SetReadOnly(DataTable dt, bool bReadOnly, params string[] arrColName)
    {
        for (int i = 0; i <= arrColName.Length - 1; i++)
        {
            dt.Columns[arrColName[i]].ReadOnly = bReadOnly;
        }
        dt.AcceptChanges();
    }

    public static DataRow DataTable_GetRow(DataTable dt)
    {
        if (dt == null || dt.Rows.Count == 0)
        {
            return null;
        }
        else
        {
            return dt.Rows[0];
        }
    }

    public static void DataTable_UpdateRow(DataTable dt, string rowFilter, string fieldName, object fieldValue)
    {
        string oldFilter = dt.DefaultView.RowFilter;
        dt.DefaultView.RowFilter = rowFilter;
        for (int i = 0; i <= dt.DefaultView.Count - 1; i++)
        {
            dt.DefaultView[i][fieldName] = fieldValue;
        }
        dt.DefaultView.RowFilter = oldFilter;
    }

    public static void DataTable_AppendRow(DataTable dt, string rowFilter, string fieldName, decimal fieldValue)
    {
        if (!Type_IsNumeric(dt.Columns[fieldName].DataType))
        {
            throw new ArgumentException("DataType of this column is not numeric'" + fieldName + "'", "fieldName");
        }
        string oldFilter = dt.DefaultView.RowFilter;
        dt.DefaultView.RowFilter = rowFilter;
        for (int i = 0; i <= dt.DefaultView.Count - 1; i++)
        {
            dt.DefaultView[i][fieldName] = DB_GetValue(dt.DefaultView[i][fieldName], 0) + fieldValue;
        }
        dt.DefaultView.RowFilter = oldFilter;
    }

    public static void DataTable_RowNumber(DataTable dt)
    {
        if (!dt.Columns.Contains("RN"))
            dt.Columns.Add("RN", typeof(Int32));
        for (int i = 0; i <= dt.DefaultView.Count - 1; i++)
        {
            dt.DefaultView[i].Row["RN"] = i + 1;
        }
        dt.AcceptChanges();
    }

    public static void DataTable_ExProperties(DataTable dt)
    {
        //Ham nay chua su dung duoc vi can phai lam ket noi de lay ra danh sach ten truong cua bang trong database
        /*
        if (dt == null)
            throw new ArgumentNullException("dt");
        if (string.IsNullOrEmpty(dt.TableName))
            throw new ArgumentNullException("dt.TableName");
        //
        DataTable mDataTable = SystemController.Instance().Table_GetField(dt.TableName);
        //
        foreach (DataRow drColumn in mDataTable.Rows)
        {
            if (dt.Columns.Contains(drColumn["Column_Name"].ToString()))
            {
                dt.Columns[drColumn["Column_Name"].ToString()].ExtendedProperties.Add("DATA_TYPE", drColumn["DATA_TYPE"]);
                dt.Columns[drColumn["Column_Name"].ToString()].ExtendedProperties.Add("DATA_LENGTH", drColumn["DATA_LENGTH"]);
                dt.Columns[drColumn["Column_Name"].ToString()].ExtendedProperties.Add("DATA_SCALE", DB_GetValue(drColumn["DATA_SCALE"], 0));
            }
        }
         */
    }
    public static DataTable ChangeRowsToColumns(DataTable myTable)
    {
        DataTable outTable = new DataTable();
        outTable.Columns.Add(myTable.Columns[0].ColumnName.ToString());
        foreach (DataRow inRow in myTable.Rows)
        {
            string newColName = inRow[0].ToString();
            outTable.Columns.Add(newColName);
        }
        for (int rCount = 1; rCount <= myTable.Columns.Count - 1; rCount++)
        {
            DataRow newRow = outTable.NewRow();
            newRow[0] = myTable.Columns[rCount].ColumnName.ToString();
            for (int cCount = 0; cCount <= myTable.Rows.Count - 1; cCount++)
            {
                string colValue = myTable.Rows[cCount][rCount].ToString();
                newRow[cCount + 1] = colValue;
            }
            outTable.Rows.Add(newRow);
        }
        return outTable;
    }
    public static DataRow DataView_FindRow(DataTable dt, string columnName, object columnValue)
    {
        return DataView_FindRow(dt, columnName, columnValue, -1);
    }

    public static DataRow DataView_FindRow(DataTable dt, string columnName, object columnValue, int execeptIndex)
    {
        return DataView_FindRow(dt.DefaultView, columnName, columnValue, execeptIndex);
    }

    public static DataRow DataView_FindRow(DataView dtView, string columnName, object columnValue)
    {
        return DataView_FindRow(dtView, columnName, columnValue, -1);
    }

    public static DataRow DataView_FindRow(DataView dtView, string columnName, object columnValue, int execeptIndex)
    {
        for (int i = 0; i <= dtView.Count - 1; i++)
        {
            if (i != execeptIndex && dtView[i][columnName] == columnValue)
            {
                return dtView[i].Row;
            }
        }
        return null;
    }

    public static DataRow DataView_FindRow(DataTable dt, string filter)
    {
        return DataView_FindRow(dt.DefaultView, filter);
    }

    public static DataRow DataView_FindRow(DataView dtView, string filter)
    {
        DataRow retVal = null;
        string oldFilter = dtView.RowFilter;
        dtView.RowFilter = filter;
        if (dtView.Count > 0)
        {
            retVal = dtView[0].Row;
        }
        dtView.RowFilter = oldFilter;
        return retVal;
    }

    public static void DataRow_FillObject(DataRow dtRow, Standard_Info objInfo)
    {
        DataRow_FillObject(dtRow, objInfo, null);
    }

    public static void DataRow_FillObject(DataRow dtRow, Standard_Info objInfo, FormatInvoker customFormat)
    {
        if (objInfo == null)
            throw new ArgumentNullException("objInfo");
        //
        string sPropertyName = null;
        Type objType = objInfo.GetType();
        PropertyInfo objProperty = default(PropertyInfo);
        foreach (DataColumn dtCol in dtRow.Table.Columns)
        {
            sPropertyName = dtCol.ColumnName;
            objProperty = Object_GetProperty(objType, sPropertyName);
            if ((objProperty != null) && objProperty.CanWrite)
            {
                object objValue = dtRow[sPropertyName];
                if (customFormat != null)
                    customFormat.Invoke(sPropertyName, ref objValue);
                if (IsDBNull(objValue))
                {
                    objProperty.SetValue(objInfo, Null.SetNull(objProperty), null);
                }
                else
                {
                    if (objProperty.PropertyType.Equals(typeof(bool)))
                    {
                        objProperty.SetValue(objInfo, Globals.Object_SetValueEx<bool>(objValue), null);
                    }
                    else
                    {
                        objProperty.SetValue(objInfo, Convert.ChangeType(objValue, objProperty.PropertyType), null);
                    }

                }
            }
        }
    }

    public static void DataRow_FillData(DataRow dtRow, Standard_Info objInfo)
    {
        DataRow_FillData(dtRow, objInfo, null);
    }

    public static void DataRow_FillData(DataRow dtRow, Standard_Info objInfo, FormatInvoker customFormat)
    {
        if (objInfo == null)
            throw new ArgumentNullException("objInfo");
        //
        string sPropertyName = null;
        Type objType = objInfo.GetType();
        PropertyInfo objProperty = default(PropertyInfo);
        foreach (DataColumn dtCol in dtRow.Table.Columns)
        {
            sPropertyName = dtCol.ColumnName;
            objProperty = Object_GetProperty(objType, sPropertyName);
            if ((objProperty != null) && objProperty.CanRead)
            {
                object objValue = objProperty.GetValue(objInfo, null);
                if (customFormat != null)
                    customFormat.Invoke(sPropertyName, ref objValue);
                if (dtCol.AllowDBNull)
                {
                    dtRow[sPropertyName] = DB_GetNull(objValue);
                }
                else
                {
                    dtRow[sPropertyName] = objValue;
                }
            }
        }
    }

    public static void DataRow_Copy(DataRow dtRowSrc, DataRow dtRowDest)
    {
        DataRow_Copy(dtRowSrc, dtRowDest, null);
    }

    public static void DataRow_Copy(DataRow dtRowSrc, DataRow dtRowDest, FormatInvoker formatInvoke)
    {
        object oValue = null;
        foreach (DataColumn dtCol in dtRowSrc.Table.Columns)
        {
            if (dtRowDest.Table.Columns.Contains(dtCol.ColumnName))
            {
                oValue = dtRowSrc[dtCol.ColumnName];
                if (formatInvoke != null)
                    formatInvoke.Invoke(dtCol.ColumnName, ref oValue);
                dtRowDest[dtCol.ColumnName] = oValue;
            }
        }
    }

    public static DataColumn DataColumn_New(string columnName, Type columnType)
    {
        return DataColumn_New(columnName, columnType, false, null);
    }

    public static DataColumn DataColumn_New(string columnName, Type columnType, string columnExp)
    {
        return new DataColumn(columnName, columnType, columnExp);
    }

    public static DataColumn DataColumn_New(string columnName, Type columnType, bool columnRequired)
    {
        return DataColumn_New(columnName, columnType, columnRequired, null);
    }

    public static DataColumn DataColumn_New(string columnName, Type columnType, bool columnRequired, object columnDefault)
    {
        DataColumn retVal = new DataColumn(columnName, columnType);
        retVal.AllowDBNull = !columnRequired;
        if (columnDefault != null)
            retVal.DefaultValue = columnDefault;
        return retVal;
    }

    public static object Reader_GetValue(IDataReader rd, string sItemName)
    {
        int iIndex = 0;
        iIndex = Reader_ColumnIndex(rd, sItemName);
        if (iIndex >= 0)
        {
            return rd[iIndex];
        }
        else
        {
            return null;
        }
    }

    public static object Reader_GetValue(IDataReader rd, string sItemName, System.Collections.Generic.Dictionary<string, int> dicColumn)
    {
        int iIndex = 0;
        if (dicColumn.ContainsKey(sItemName))
        {
            iIndex = dicColumn[sItemName];
        }
        else
        {
            iIndex = Reader_ColumnIndex(rd, sItemName);
            dicColumn.Add(sItemName, iIndex);
        }
        if (iIndex >= 0)
        {
            return rd[iIndex];
        }
        else
        {
            return null;
        }
    }

    public static Dictionary<string, int> Reader_ColumnList(IDataReader rd)
    {
        System.Collections.Generic.Dictionary<string, int> rt = new System.Collections.Generic.Dictionary<string, int>();
        for (int i = 0; i <= rd.FieldCount - 1; i++)
        {
            rt.Add(rd.GetName(i), i);
        }
        return rt;
    }

    public static int Reader_ColumnIndex(IDataReader rd, string sColumn)
    {
        //For i As Integer = 0 To rd.FieldCount - 1
        //    If sColumn.Equals(rd.GetName(i), StringComparison.CurrentCultureIgnoreCase) Then
        //        Return i
        //    End If
        //Next
        //Return -1
        try
        {
            return rd.GetOrdinal(sColumn);
        }
        catch
        {
            return -1;
        }
    }

    public static void Reader_Close(IDataReader obj)
    {
        if (obj == null)
            return;
        obj.Close();
        obj.Dispose();
    }

    public static void Object_SetValue(object objSource, ref object objDest)
    {
        //Purpose: 
        //   Sử dụng để gán giá trị từ kiểu dữ liệu này sang kiểu dữ liệu khác
        //Parameters: 
        //   objSource : dữ liệu nguồn
        //   objDest   : dữ liệu đích
        //Notes:
        //   
        object sValue = null;
        if ((objSource != null))
        {
            //
            if (objSource.GetType().Namespace == "System.Windows.Forms")
                throw new Exception("Param objSource don't support type " + objSource.GetType().Name);
            //
            if (objDest.GetType().Name == objSource.GetType().Name)
            {
                objDest = objSource;
                return;
            }
            else if (object.ReferenceEquals(objSource, DBNull.Value))
            {
                objDest = Null.SetNull(DBNull.Value, objDest);
                return;
            }
            else
            {
                sValue = objSource.ToString();
            }
        }
        else
        {
            sValue = "";
        }
        if (objDest == null)
        {
            objDest = sValue;
        }
        else
        {
            objDest = Object_SetValueEx(sValue, objDest.GetType().Name, false);
        }
    }

    public static bool Type_IsNumeric(Type type)
    {
        TypeCode typeCode = Type.GetTypeCode(type);
        //The TypeCode of numerical types are between SByte (5) and Decimal (15).
        return (int)typeCode >= 5 && (int)typeCode <= 15;
    }

    public static bool Type_IsNumbericOth(object o)
    {
        return (o is System.ValueType && !(o is System.Boolean) && !(o is System.Enum));
    }

    public static T Object_GetValue<T>(object sValue)
    {
        T objReturn = default(T);
        if (sValue == null)
        {
            return (T)Null.GetNull(sValue, Null.GetNullOfType<T>());
        }
        else
        {
            if ((objReturn == null))
            {
                return (T)Object_SetValueEx(sValue, "String", false);
            }
            else
            {
                return (T)Object_SetValueEx(sValue, objReturn.GetType().Name, false);
            }
        }
    }

    public static T Object_GetValue<T>(object sValue, T nullValue)
    {
        T objReturn = default(T);
        if (sValue == null || Globals.IsDBNull(sValue))
        {
            return nullValue;
        }
        else
        {
            if ((objReturn == null))
            {
                return (T)Object_SetValueEx(sValue, "String", false);
            }
            else
            {
                objReturn = (T)Object_SetValueEx(sValue, objReturn.GetType().Name, false);
                if (Null.IsNull(objReturn))
                {
                    return nullValue;
                }
                else
                {
                    return objReturn;
                }
            }
        }
    }

    public static object Object_GetValue(object sValue, string sDataType, object nullValue)
    {
        object objReturn = null;
        if (sValue == null || Globals.IsDBNull(sValue))
        {
            return nullValue;
        }
        else
        {
            objReturn = Object_SetValueEx(sValue, sDataType, false);
            if (Null.IsNull(objReturn))
            {
                return nullValue;
            }
            else
            {
                return objReturn;
            }
        }
    }

    public static T Object_SetValueEx<T>(object sValue)
    {
        T objReturn = default(T);
        if (sValue == null)
        {
            return Null.GetNullOfType<T>();
        }
        else
        {
            if ((objReturn == null))
            {
                return (T)Object_SetValueEx(sValue, "String", false);
            }
            else
            {
                return (T)Object_SetValueEx(sValue, objReturn.GetType().Name, false);
            }
        }
    }
    public static object Object_SetValueEx(object inputValue, string outputType, bool bForDB = false)
    {
        if (bForDB == null) bForDB = false;
        object outputValue = null;
        string inputType = null;
        if ((inputValue != null))
            inputType = inputValue.GetType().Name.ToUpper();
        outputType = outputType.ToUpper();
        if (inputType == outputType)
        {
            return inputValue;
        }
        else
        {
            if (Array.IndexOf<String>(cs_Type_DateTime, outputType) >= 0)// cs_Type_DateTime.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_DateTime, inputType) >= 0)//cs_Type_DateTime.Contains(inputType))
                    return inputValue;

                DateTime outPutDate = new DateTime();

                if (!Date_TryParseEx(inputValue.ToString(), ref outPutDate))
                {
                    if (bForDB)
                    {
                        outputValue = DBNull.Value;
                    }
                    else
                    {
                        outputValue = Null.NullDate;
                    }
                }
                else
                    outputValue = outPutDate;
            }
            else if (Array.IndexOf<String>(cs_Type_Long, outputType) >= 0)// if (cs_Type_Long.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_Long, inputType) >= 0) //if (cs_Type_Long.Contains(inputType))
                    return inputValue;
                if ((inputValue != null))
                    inputValue = inputValue.ToString().Replace(CS_DIGIT_GROUP_SYMBOL, "");
                if (Globals.IsNumeric(inputValue))
                {
                    outputValue = decimal.ToInt64(decimal.Parse(inputValue.ToString()));
                }
                else
                {
                    if (bForDB)
                    {
                        outputValue = DBNull.Value;
                    }
                    else
                    {
                        outputValue = Null.NullLong;
                    }
                }
            }
            else if (Array.IndexOf<String>(cs_Type_Integer, outputType) >= 0) //if (cs_Type_Integer.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_Integer, inputType) >= 0) //if (cs_Type_Integer.Contains(inputType))
                    return inputValue;
                if ((inputValue != null))
                    inputValue = inputValue.ToString().Replace(CS_DIGIT_GROUP_SYMBOL, "");
                if (Globals.IsNumeric(inputValue))
                {
                    outputValue = decimal.ToInt32(decimal.Parse(inputValue.ToString()));
                }
                else
                {
                    if (bForDB)
                    {
                        outputValue = DBNull.Value;
                    }
                    else
                    {
                        outputValue = Null.NullInteger;
                    }
                }
            }
            else if (Array.IndexOf<String>(cs_Type_Short, outputType) >= 0) //if (cs_Type_Short.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_Short, inputType) >= 0) //if (cs_Type_Short.Contains(inputType))
                    return inputValue;
                if ((inputValue != null))
                    inputValue = inputValue.ToString().Replace(CS_DIGIT_GROUP_SYMBOL, "");
                if (Globals.IsNumeric(inputValue))
                {
                    outputValue = decimal.ToInt16(decimal.Parse(inputValue.ToString()));
                }
                else
                {
                    if (bForDB)
                    {
                        outputValue = DBNull.Value;
                    }
                    else
                    {
                        outputValue = Null.NullShort;
                    }
                }
            }
            else if (Array.IndexOf<String>(cs_Type_Byte, outputType) >= 0) //if (cs_Type_Byte.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_Byte, inputType) >= 0) //if (cs_Type_Byte.Contains(inputType))
                    return inputValue;
                if ((inputValue != null))
                    inputValue = inputValue.ToString().Replace(CS_DIGIT_GROUP_SYMBOL, "");
                if (Globals.IsNumeric(inputValue))
                {
                    outputValue = decimal.ToByte(decimal.Parse(inputValue.ToString()));
                }
                else
                {
                    if (bForDB)
                    {
                        outputValue = DBNull.Value;
                    }
                    else
                    {
                        outputValue = byte.MinValue;
                    }
                }
            }
            else if (Array.IndexOf<String>(cs_Type_Double, outputType) >= 0) //if (cs_Type_Double.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_Double, inputType) >= 0) //if (cs_Type_Double.Contains(inputType))
                    return inputValue;
                if ((inputValue != null))
                    inputValue = inputValue.ToString().Replace(CS_DIGIT_GROUP_SYMBOL, "");
                if (Globals.IsNumeric(inputValue))
                {
                    outputValue = double.Parse(inputValue.ToString());
                }
                else
                {
                    if (bForDB)
                    {
                        outputValue = DBNull.Value;
                    }
                    else
                    {
                        outputValue = Null.NullDouble;
                    }
                }
            }
            else if (Array.IndexOf<String>(cs_Type_Single, outputType) >= 0) //if (cs_Type_Single.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_Single, inputType) >= 0) //if (cs_Type_Single.Contains(inputType))
                    return inputValue;
                if ((inputValue != null))
                    inputValue = inputValue.ToString().Replace(CS_DIGIT_GROUP_SYMBOL, "");
                if (Globals.IsNumeric(inputValue))
                {
                    outputValue = float.Parse(inputValue.ToString());
                }
                else
                {
                    if (bForDB)
                    {
                        outputValue = DBNull.Value;
                    }
                    else
                    {
                        outputValue = Null.NullSingle;
                    }
                }
            }
            else if (Array.IndexOf<String>(cs_Type_Decimal, outputType) >= 0) //if (cs_Type_Decimal.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_Decimal, inputType) >= 0) //if (cs_Type_Decimal.Contains(inputType))
                    return inputValue;
                if ((inputValue != null))
                    inputValue = inputValue.ToString().Replace(CS_DIGIT_GROUP_SYMBOL, "");
                if (Globals.IsNumeric(inputValue))
                {
                    outputValue = decimal.Parse(inputValue.ToString());
                }
                else
                {
                    if (bForDB)
                    {
                        outputValue = DBNull.Value;
                    }
                    else
                    {
                        outputValue = Null.NullDecimal;
                    }
                }
            }
            else if (Array.IndexOf<String>(cs_Type_String, outputType) >= 0) //if (cs_Type_String.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_String, inputType) >= 0) //if (cs_Type_String.Contains(inputType))
                    return inputValue;
                if (object.ReferenceEquals(inputValue, DBNull.Value) || inputValue == null)
                {
                    outputValue = "";
                }
                else
                {
                    //Convert array to string
                    if (inputType.EndsWith("[]"))
                    {
                        outputValue = (inputValue).ToString();
                    }
                    else
                    {
                        outputValue = inputValue.ToString();
                    }
                }
                if (bForDB && string.IsNullOrEmpty(outputValue.ToString()))
                {
                    outputValue = DBNull.Value;
                }
            }
            else if (Array.IndexOf<String>(cs_Type_Boolean, outputType) >= 0) //if (cs_Type_Boolean.Contains(outputType))
            {
                if (Array.IndexOf<String>(cs_Type_Boolean, inputType) >= 0) //if (cs_Type_Boolean.Contains(inputType))
                    return inputValue;
                if (object.ReferenceEquals(inputValue, DBNull.Value) || inputValue == null)
                {
                    outputValue = false;
                }
                else
                {
                    bool boolValue;
                    if (!bool.TryParse(inputValue.ToString(), out boolValue))
                    {
                        switch (inputValue.ToString().ToUpper())
                        {
                            case "YES":
                            case "Y":
                            case "TRUE":
                            case "T":
                            case "1":
                                outputValue = true;
                                break;
                            default:
                                outputValue = false;
                                break;
                        }
                    }
                    else
                        outputValue = boolValue;
                }
            }
            else if ("GUID".Contains(outputType))
            {
                if (string.IsNullOrEmpty(inputValue.ToString()))
                {
                    outputValue = Null.NullGuid;
                }
                else
                {
                    try
                    {
                        outputValue = new Guid(inputValue.ToString());
                    }
                    catch
                    {
                        outputValue = Null.NullGuid;
                    }
                }
                if (bForDB && (Guid)outputValue == Null.NullGuid)
                {
                    outputValue = DBNull.Value;
                }
            }
            else
            {
                if (object.ReferenceEquals(inputValue, DBNull.Value))
                {
                    outputValue = null;
                }
                else
                {
                    outputValue = inputValue;
                }
            }
        }
        return outputValue;
    }

    public static string Object_GetDisplayValue(object objSource)
    {
        return Object_GetDisplayValue(objSource, "");
    }

    public static string Object_GetDisplayValue(object objSource, string sNullValue)
    {
        return Object_GetDisplayValue(objSource, sNullValue, true);
    }

    public static string Object_GetDisplayValue(object objSource, string sNullValue, bool bFormat)
    {
        //Purpose: 
        //   Customize ToString 
        //Parameters: 
        //   objSource : dữ liệu nguồn
        //Notes:
        //   Đối với dữ liệu kiểu Date sẽ tự chuyển thành CS_DISPLAY_DATE_FORMAT
        //   Đối với dữ liệu kiểu Numeric sẽ tự format 0,000.00 và tự động bỏ các số 0 thừa

        if (objSource is bool)
        {
            if (Convert.ToBoolean(objSource) == true)
            {
                return "Yes";
            }
            else
            {
                return "No";
            }
        }
        else
        {
            if (Null.IsNull(objSource))
            {
                return sNullValue;
            }
            else
            {
                if (objSource is System.DateTime)
                {
                    if (bFormat)
                    {
                        return Convert.ToDateTime(objSource).ToString(CS_DISPLAY_DATE_FORMAT);
                    }
                    else
                    {
                        return Convert.ToDateTime(objSource).ToShortDateString();
                    }
                }
                else
                {
                    if (bFormat && (!(objSource is string) && Globals.IsNumeric(objSource)))
                    {
                        objSource = FormatNumberEx((decimal)objSource, (short)CS_DECIMAL_SCALE);
                    }
                    return objSource.ToString();
                }
            }
        }
    }

    public static string Enum_GetName(Enum eValue)
    {
        return Enum.GetName(eValue.GetType(), eValue);
    }

    public static string FormatNumberEx(decimal objSource, short iDecimal)
    {
        string sFormat = "#,##0";
        if (iDecimal > 0)
        {
            sFormat += "." + String.Format("0", iDecimal);
        }
        else if (iDecimal <= 0)
        {
            objSource = objSource / (decimal)Math.Pow(10, (-iDecimal));
            //Else
            sFormat = "#,##0";
        }
        string sReturn = objSource.ToString(sFormat);
        //FormatNumber(objSource, , TriState.False)
        string sDecChar = null;
        sDecChar = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
        //
        int iPos = sReturn.ToString().LastIndexOf(sDecChar);
        if (iPos > -1)
        {
            string sDecNum = sReturn.ToString().Substring(iPos);
            while (!(string.IsNullOrEmpty(sDecNum)))
            {
                if (sDecNum.Substring(sDecNum.Length - 1) != "0")
                {
                    break; // TODO: might not be correct. Was : Exit Do
                }
                else
                {
                    sDecNum = sDecNum.Substring(0, sDecNum.Length - 1);
                }
            }
            if (sDecNum == sDecChar)
                sDecNum = "";
            sReturn = sReturn.Substring(0, iPos) + sDecNum;
            if (sReturn.Length == 0)
                sReturn = "0";
        }
        return sReturn;
    }

    public static string Time_GetValue(System.DateTime objSource, bool bSuppressNull)
    {
        if (bSuppressNull == null) bSuppressNull = true;
        string sReturn = objSource.ToString("HH:mm");
        if (bSuppressNull && sReturn == "00:00")
        {
            sReturn = "";
        }
        return sReturn;
    }

    public static void DateTime_SetValue(string objSource, ref System.DateTime objDest)
    {
        objDest = Date_ParseEx(objSource);
    }

    public static object Object_GetPropertyValue(object objObject, string sPropertyName)
    {
        if (objObject == null)
            throw new ArgumentNullException("objObject");
        PropertyInfo objProp = Object_GetProperty(objObject.GetType(), sPropertyName);
        object objReturn = null;
        if ((objProp != null) && objProp.CanRead)
        {
            objReturn = objProp.GetValue(objObject, null);
        }
        return objReturn;
    }

    public static object Object_GetPropertyValue(object objObject, int iPropertyIndex)
    {
        if (objObject == null)
            throw new ArgumentNullException("objObject");
        Type objType = objObject.GetType();
        PropertyInfo objProperty = (PropertyInfo)CBO.GetPropertyInfo(objType)[iPropertyIndex];
        //objType.GetProperties.GetValue(iPropertyIndex)
        if (objProperty == null)
        {
            return null;
        }
        else
        {
            return objProperty.GetValue(objObject, null);
        }
    }

    public static PropertyInfo Object_GetProperty(Type objType, string sPropertyName)
    {
        PropertyInfo objReturn = objType.GetProperty(sPropertyName);
        //Ignore Case
        if (objReturn == null)
        {
            ;
            List<PropertyInfo> arr = ConvertArrayToList<PropertyInfo>(CBO.GetPropertyInfo(objType));
            foreach (PropertyInfo obj in arr)
            {
                if (obj.Name.ToUpper() == sPropertyName.ToUpper())
                {
                    objReturn = obj;
                    break; // TODO: might not be correct. Was : Exit For
                }
            }
        }
        return objReturn;
    }

    public static int Object_GetPropertyIndex(Type objType, ref string sPropertyName)
    {
        List<PropertyInfo> arr = ConvertArrayToList<PropertyInfo>(CBO.GetPropertyInfo(objType));
        PropertyInfo objReturn = objType.GetProperty(sPropertyName);
        //Ignore Case
        if (objReturn == null)
        {
            return Object_GetPropertyIndex(arr, ref sPropertyName);
        }
        else
        {
            return arr.IndexOf(objReturn);
        }
    }

    public static int Object_GetPropertyIndex(List<PropertyInfo> arrProperty, ref string sPropertyName)
    {
        PropertyInfo objReturn = default(PropertyInfo);
        for (int i = 0; i <= arrProperty.Count - 1; i++)
        {
            objReturn = arrProperty[i];
            if (objReturn.Name.ToUpper() == sPropertyName.ToUpper())
            {
                sPropertyName = objReturn.Name;
                return i;
            }
        }
        return -1;
    }

    public static bool Object_Compare(object Object1, object Object2)
    {
        //Purpose: 
        //   Hỗ trợ cho phần SetComboValue
        //   So sánh 2 Object dựa trên Properties
        //Parameters: 
        //
        //Notes
        //   Chú ý nếu trong phần định nghĩa prototye của Object 
        //   có trường PK lưu tên của thuộc tính PK
        //   thì khi compare chỉ compare các thuộc tính PK này
        bool mReturn = true;
        PropertyInfo objProperty = default(PropertyInfo);

        objProperty = Object1.GetType().GetProperty("PK");


        if ((objProperty != null))
        {
            string[] arrPK = objProperty.GetValue(Object1, null).ToString().Split(';');
            for (long i = 0; i <= arrPK.GetUpperBound(0); i++)
            {
                objProperty = Object1.GetType().GetProperty(arrPK[i]);
                if (objProperty == null)
                {
                    mReturn = false;
                    break; // TODO: might not be correct. Was : Exit For
                }
                else
                {
                    if (objProperty.GetValue(Object1, null) != objProperty.GetValue(Object2, null))
                    {
                        mReturn = false;
                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
            }
        }
        if (!mReturn)
        {
            foreach (PropertyInfo _objProperty in Object1.GetType().GetProperties())
            {
                if (_objProperty.GetValue(Object1, null) != _objProperty.GetValue(Object2, null))
                {
                    mReturn = false;
                    break; // TODO: might not be correct. Was : Exit For
                }
            }
        }
        return mReturn;

    }

    public static T DataRow_FillObject<T>(DataRow dtRow)
    {
        object objObject = Activator.CreateInstance<T>();
        DataRow_FillObject(dtRow, ref objObject);
        return (T)objObject;
    }

    public static object DataRow_FillObject(DataRow dtRow, Type objType)
    {
        object objObject = Activator.CreateInstance(objType);
        DataRow_FillObject(dtRow, ref objObject);
        return objObject;
    }

    public static void DataRow_FillObject(DataRow dtRow, ref object objObject)
    {
        //
        Type objType = objObject.GetType();
        PropertyInfo objProperty = default(PropertyInfo);
        PropertyInfo[] arrProperty = objType.GetProperties();
        string sKey = objType.Name + "_" + dtRow.Table.Columns.Count.ToString();
        System.Collections.Generic.List<int> dicIndex = null;
        //----------------
        if ((m_cacheTableColumn != null) && m_cacheTableColumn.ContainsKey(sKey))
        {
            dicIndex = m_cacheTableColumn[sKey];
            for (int iPro = 0; iPro <= dicIndex.Count - 1; iPro++)
            {
                int iField = dicIndex[iPro];
                if (iField == -1)
                    continue;
                Object_SetPropertyValue(ref objObject, arrProperty[iPro], dtRow[iField]);
            }
        }
        else
        {
            dicIndex = new System.Collections.Generic.List<int>();
            for (int iProIndex = 0; iProIndex <= arrProperty.Length - 1; iProIndex++)
            {
                objProperty = arrProperty[iProIndex];
                int iIndex = 0;
                if (objProperty.CanWrite)
                {
                    iIndex = dtRow.Table.Columns.IndexOf(objProperty.Name);
                    if (iIndex > -1)
                    {
                        Object_SetPropertyValue(ref objObject, objProperty, dtRow[iIndex]);
                    }
                }
                else
                {
                    iIndex = -1;
                }
                dicIndex.Add(iIndex);
            }
            if (m_cacheTableColumn == null)
                m_cacheTableColumn = new Dictionary<string, List<int>>();
            m_cacheTableColumn.Add(sKey, dicIndex);
        }
    }

    public static void Object_SetPropertyValue(ref object objObject, PropertyInfo objPropertyInfo, object objValue)
    {
        if (IsDBNull(objValue))
        {
            // translate Null value
            objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null);
        }
        else
        {
            try
            {
                // try implicit conversion first
                objPropertyInfo.SetValue(objObject, objValue, null);
            }
            catch
            {
                Type objPropertyType = null;
                // business object info class member data type does not match datareader member data type
                objPropertyType = objPropertyInfo.PropertyType;
                try
                {
                    //need to handle enumeration conversions differently than other base types
                    if (objPropertyType.IsEnum)
                    {
                        // check if value is numeric and if not convert to integer ( supports databases like Oracle )
                        if (IsNumeric(objValue))
                        {
                            objPropertyInfo.SetValue(objObject, System.Enum.ToObject(objPropertyType, Convert.ToInt32(objValue)), null);
                        }
                        else
                        {
                            objPropertyInfo.SetValue(objObject, System.Enum.ToObject(objPropertyType, objValue), null);
                        }
                    }
                    else
                    {
                        // try explicit conversion
                        objPropertyInfo.SetValue(objObject, Convert.ChangeType(objValue, objPropertyType), null);
                    }
                }
                catch
                {
                    if (objPropertyType.Name == "Boolean")
                    {
                        objPropertyInfo.SetValue(objObject, Convert.ToBoolean(objValue), null);
                    }
                    else
                    {
                        objPropertyInfo.SetValue(objObject, Convert.ChangeType(objValue, objPropertyType), null);
                    }
                }
            }
        }
    }

    public static List<object> DataTable_FillList(DataTable dtTable, Type objType)
    {
        if (dtTable.Rows.Count == 0)
            return null;
        List<object> retVal = new List<object>();
        foreach (DataRow dr in dtTable.Rows)
        {
            object objObject = Activator.CreateInstance(objType);
            DataRow_FillObject(dr, ref objObject);
            retVal.Add(objObject);
        }
        return retVal;
    }

    public static List<T> DataTable_FillList<T>(DataTable dtTable)
    {
        if (dtTable.Rows.Count == 0)
            return null;
        List<T> retVal = new List<T>();
        foreach (DataRow dr in dtTable.Rows)
        {
            object objObject = default(T);
            if (typeof(T).Namespace == "System")
            {
                objObject = DB_GetValue<T>(dr[0]);
            }
            else
            {
                objObject = Activator.CreateInstance<T>();
                DataRow_FillObject(dr, ref objObject);
            }
            retVal.Add((T)objObject);
        }
        return retVal;
    }

    public static bool Date_TryParseEx(string sValue, string sFormat, ref System.DateTime dReturn)
    {
        if (System.DateTime.TryParseExact(sValue, sFormat, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out dReturn))
            return true;
        else
            return false;
    }

    public static bool Date_TryParseEx(string sValue, ref System.DateTime dReturn)
    {
        if (System.DateTime.TryParseExact(sValue, CS_EDIT_DATETIME_FORMAT, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out dReturn))
            return true;
        else if (System.DateTime.TryParseExact(sValue, CS_DISPLAY_DATETIME_FORMAT, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out dReturn))
            return true;
        else if (System.DateTime.TryParseExact(sValue, CS_EDIT_DATE_FORMAT, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out dReturn))
            return true;
        else if (System.DateTime.TryParseExact(sValue, CS_DISPLAY_DATE_FORMAT, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out dReturn))
            return true;
        else
        {
            if (System.DateTime.TryParse(sValue, out dReturn))
                return true;
        }
        return false;
    }

    public static void Date_FixString(ref string sValue, bool bShortDate)
    {
        if (bShortDate == null) bShortDate = false;
        DateTime dtOut = DateTime.MinValue;
        if (!System.DateTime.TryParse(sValue, out dtOut) || sValue.Length > 4)
        {
            sValue = sValue.Replace(" ", "/");
            sValue = sValue.Replace("-", "/");
            if (sValue.Length == 8 && Regex.IsMatch(sValue, "\\b\\d{8}\\b"))
            {
                sValue = sValue.Substring(0, 2) + "/" + sValue.Substring(2, 2) + "/" + sValue.Substring(4, 4);
            }
            else if (sValue.Length == 6 && Regex.IsMatch(sValue, "\\b\\d{6}\\b"))
            {
                System.DateTime dt = System.DateTime.Parse("01/01/" + sValue.Substring(4, 2));
                sValue = sValue.Substring(0, 2) + "/" + sValue.Substring(2, 2) + "/" + dt.Year;
            }
            else if (sValue.Length == 4 && Regex.IsMatch(sValue, "\\b\\d{4}\\b"))
            {
                sValue = sValue.Substring(0, 2) + "/" + sValue.Substring(2, 2);
                if (!bShortDate)
                    sValue = sValue + "/" + DateTime.Today.Year;
            }
            else if (sValue.Length == 5 && Regex.IsMatch(sValue, "\\b\\d{2}\\/\\d{2}\\b"))
            {
                if (!bShortDate)
                    sValue = sValue + "/" + DateTime.Today.Year;
            }
            else if (sValue.Length == 2 && Regex.IsMatch(sValue, "\\b\\d{2}\\b"))
            {
                if (int.Parse(sValue) < 32)
                {
                    sValue += "/" + DateTime.Today.Month.ToString().PadLeft(2, '0');
                    if (!bShortDate)
                        sValue = sValue + "/" + DateTime.Today.Year;
                }
            }
        }
    }

    public static void Time_FixString(ref string sValue)
    {
        DateTime dtOut = DateTime.MinValue;
        if (!System.DateTime.TryParse(sValue, out dtOut) || sValue.Length > 0)
        {
            if (sValue.Length == 4 && Regex.IsMatch(sValue, "\\b\\d{4}\\b"))
            {
                sValue = sValue.Substring(0, 2) + ":" + sValue.Substring(2, 2);
            }
            else if (sValue.Length == 3 && Regex.IsMatch(sValue, "\\b\\d{3}\\b"))
            {
                sValue = sValue.Substring(0, 1) + ":" + sValue.Substring(1, 2);
            }
            else if (sValue.Length == 2 && Regex.IsMatch(sValue, "\\b\\d{2}\\b"))
            {
                sValue = sValue + ":00";
            }
        }
    }

    public static DateTime Time_ParseEx(string dateValue, string timeValue)
    {
        DateTime retVal = System.DateTime.MinValue;
        if (Date_TryParseEx(dateValue, ref retVal))
        {
            return Time_ParseEx(retVal, timeValue);
        }
        else
        {
            return retVal;
        }
    }

    public static DateTime Time_ParseEx(DateTime dateValue, string timeValue)
    {
        DateTime retVal = System.DateTime.MinValue;
        if (timeValue != null)
            timeValue = timeValue.Trim();
        if (string.IsNullOrEmpty(timeValue))
            return retVal;
        while (timeValue.EndsWith("+"))
        {
            timeValue = timeValue.Substring(0, timeValue.Length - 1);
            dateValue = dateValue.AddDays(1);
        }
        while (timeValue.EndsWith("-"))
        {
            timeValue = timeValue.Substring(0, timeValue.Length - 1);
            dateValue = dateValue.AddDays(-1);
        }
        Time_FixString(ref timeValue);
        if (Date_TryParseEx(timeValue, ref retVal))
        {
            retVal = dateValue.Date.AddHours(retVal.Hour).AddMinutes(retVal.Minute);
        }
        return retVal;
    }

    public static string Time_ToStringEx(System.DateTime dateValue, System.DateTime timeValue)
    {
        string retVal = null;
        if (Null.IsNull(timeValue))
        {
            retVal = "";
        }
        else
        {
            retVal = timeValue.ToString(CS_DISPLAY_TIME_FORMAT);
            if (timeValue.Date > dateValue.Date)
            {
                //retVal += "".PadRight((timeValue.Date - dateValue.Date).TotalDays, "+")
                retVal += "+";
                if ((timeValue.Date - dateValue.Date).TotalDays > 1)
                    retVal += (timeValue.Date - dateValue.Date).TotalDays.ToString();
            }
            else if (timeValue.Date < dateValue.Date)
            {
                //retVal += "".PadRight((dateValue.Date - timeValue.Date).TotalDays, "-")
                retVal += "-";
                if ((dateValue.Date - timeValue.Date).TotalDays > 1)
                    retVal += (dateValue.Date - timeValue.Date).TotalDays.ToString();
            }
        }
        return retVal;
    }

    public static DateTime Date_ParseEx(string sValue, string sFormat)
    {
        System.DateTime mDate = default(System.DateTime);
        if (System.DateTime.TryParseExact(sValue, sFormat, System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AdjustToUniversal, out mDate))
        {
            return mDate;
        }
        else
        {
            return Null.NullDate;
        }
    }

    private static DateTime Date_ParseEx(string sValue)
    {
        System.DateTime mDate = default(System.DateTime);
        if (Date_TryParseEx(sValue, ref mDate))
        {
            return mDate;
        }
        else
        {
            if (System.DateTime.TryParse(sValue, out mDate))
            {
                return mDate;
            }
            else
            {
                return Null.NullDate;
            }
        }
    }

    public static decimal Decimal_Round(decimal dValue, decimal dRound)
    {
        decimal dDivide = (1 / dRound);
        //0.05
        decimal retVal = Math.Round(dValue * dDivide) / dDivide;
        if (retVal < dValue)
            retVal += dRound;
        return retVal;
    }

    public static string HashPassword(string Password)
    {
        return FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "SHA1");
    }

    public static DataTable ReadXML(string pathfilename)
    {
        //Đọc Data từ file XML vào biến DataTable toàn cục
        DataSet dsParameter = new DataSet();
        dsParameter.ReadXml(pathfilename, XmlReadMode.ReadSchema);
        return dsParameter.Tables[0];
    }

    public static bool XMLFileFound(string pathfilename)
    {
        //Kiểm tra xem đã tồn tại file này chưa.
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        try
        {
            xmlDoc.Load(pathfilename);
        }
        catch (System.IO.FileNotFoundException)
        {
            return false;
        }
        return true;
    }

    public static void WriteXML()
    {
        string pathfilename = System.IO.Path.GetTempPath() + "\\" + "test.xls"; ;
        if (!XMLFileFound(pathfilename))
        {
            DataSet ds = new DataSet();
            ds.WriteXml(pathfilename, XmlWriteMode.WriteSchema);
        }
    }

    public static string TransformCode(string strValue)
    {
        //Chỉ lấy số hoặc chữ trong chuỗi
        return Regex.Replace(strValue.Trim(), @"[^0-9a-zA-Z]", "");
        //return Regex.Replace(strValue.Trim(), @"?[_\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}][\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]*","");

        //string ValidChars = "aAeEoOuUiIdDyY"+
        //                                "áàạảãâấầậẩẫăắằặẳẵ"+
        //                                "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ"+ 
        //                                "éèẹẻẽêếềệểễ"+
        //                                "ÉÈẸẺẼÊẾỀỆỂỄ"+ 
        //                                "óòọỏõôốồộổỗơớờợởỡ"+
        //                                "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ"+ 
        //                                "úùụủũưứừựửữ"+
        //                                "ÚÙỤỦŨƯỨỪỰỬỮ"+ 
        //                                "íìịỉĩ"+
        //                                "ÍÌỊỈĨ"+ 
        //                                "đ"+
        //                                "Đ"+ 
        //                                "ýỳỵỷỹ"+
        //                                "ÝỲỴỶỸ"+
        //                                 "0123456789.,";
        //string Char;
        //string retVal = "";
        //for (int i = 0; i < strValue.Length; i++)
        //{
        //    Char = strValue.Substring(i,1);
        //    if (!ValidChars.Contains(Char))
        //    {
        //        retVal = strValue.Remove(i);
        //    }
        //}
        //return retVal;


    }

    public static string FormatCurrency(string number)
    {
        string sValue = "";
        if (number != null)
            sValue = String.Format("{0:0,0}", ToDecimal(number));
        return sValue;
    }

    public static String DateTime2StringSQL(Object str)
    {
        //Chỉ áp dụng với trường hợp gán lệnh thực thi sql, hoặc thực thi file excel (do file excel định dạng dấu dựa theo windows)
        return "N'" + ((DateTime)str).ToString("yyyy MMM dd HH:mm:ss") + "'";
    }

    public static String Number2StringSQL(Object number)
    {
        //Đưa đối tượng về chuỗi có dạng "123456.0000"
        //Chỉ áp dụng với trường hợp gán lệnh thực thi sql, hoặc thực thi file excel (do file excel định dạng dấu dựa theo windows)
        NumberFormatInfo numFormat = Thread.CurrentThread.CurrentCulture.NumberFormat;
        String retVal = number.ToString();
        retVal = retVal.Replace(numFormat.NumberGroupSeparator, "@");
        retVal = retVal.Replace(numFormat.NumberDecimalSeparator, ".");
        retVal = retVal.Replace("@", "");
        return retVal;
    }

    public static string GetKeyWord(string KeyWord)
    {
        string _keyword = "";
        if (KeyWord.Contains("'"))
            _keyword = KeyWord.Replace("'", "''");
        else
            _keyword = KeyWord;

        if (_keyword.ToLower().Contains("từ khóa"))
            _keyword = "";

        return _keyword;
    }

    public static string FomatedToVND(string str)
    {
        string cDecimal = Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencyDecimalSeparator;
        string cGroup = Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencyGroupSeparator;
        //Đổi dấu chấm dấu @
        str = str.Replace(cDecimal, "@");
        //Được chuỗi bao gồm dấu phẩy(hoặc chấm tùy theo windows) và dấu @
        //Lấy chuỗi vừa đổi rồi lại đổi những chỗ có dấu phẩy(hoặc chấm tùy theo windows) thành dấu chấm
        str = str.Replace(cGroup, ".");
        //Được chuỗi bao gồm dấu chấm và dấu @
        //Lấy chuỗi vừa đổi rồi lại đổi những chỗ có dấu @ thành dấu phẩy
        str = str.Replace("@", ",");
        return str;
    }

    public static Decimal StringVNDToNo(string strVND)
    {
        //strVND có dang: 123.456.789,12
        string str;
        str = strVND.Replace(",", ".");
        str = str.Replace(".", ",");

        Decimal outDec;
        if (Decimal.TryParse(str, out outDec))
            return outDec;
        else
            outDec = 0;
        return outDec;
    }

    public static Boolean ToBoolean(object obj)
    {
        string sValue = "";
        if (obj != null)
            sValue = obj.ToString();

        Boolean retVal = false;

        if (sValue == "1" || sValue.ToLower() == "true")
            retVal = true;
        else if (!Boolean.TryParse(sValue, out retVal))
            retVal = false;


        return retVal;
    }

    public static String ToString(object obj)
    {
        string sValue = "";
        if (obj != null)
            sValue = obj.ToString();
        return sValue;
    }

    public static Int32 ToInt32(object obj)
    {
        string sValue = "";
        if (obj != null)
            sValue = obj.ToString();
        Int32 retVal = 0;

        /*Hàm Int32.TryParse thực hiện dựa theo CurrentCulture của chương trình.
        --> Để có thể sử dụng được tốt việc UISetting từ String sang Int32 
         chỉ cần thay thế ký tự phân cách hàng nghìn thành ký tự trắng. ký tự phân cách thập phân không quan tâm
        */
        //sValue = sValue.Replace(Program.GroupSeparator, "");
        NumberFormatInfo numFormat = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat;
        //
        sValue = sValue.Replace(numFormat.NumberGroupSeparator, "");

        if (!Int32.TryParse(sValue, out retVal))
            retVal = 0;
        return retVal;
    }

    public static Int64 ToInt64(object obj)
    {
        string sValue = "";
        if (obj != null)
            sValue = obj.ToString();
        Int64 retVal = 0;

        /*Hàm Int32.TryParse thực hiện dựa theo CurrentCulture của chương trình.
        --> Để có thể sử dụng được tốt việc UISetting từ String sang Int32 
         chỉ cần thay thế ký tự phân cách hàng nghìn thành ký tự trắng. ký tự phân cách thập phân không quan tâm
        */
        //sValue = sValue.Replace(Program.GroupSeparator, "");
        NumberFormatInfo numFormat = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat;
        //
        sValue = sValue.Replace(numFormat.NumberGroupSeparator, "");

        if (!Int64.TryParse(sValue, out retVal))
            retVal = 0;
        return retVal;
    }

    public static Decimal ToDecimal(object obj)
    {
        string sValue = "";
        if (obj != null)
            sValue = obj.ToString();

        Decimal retVal = 0;

        /*Hàm Decimal.TryParse thực hiện dựa theo CurrentCulture của chương trình.
        --> Để có thể sử dụng được tốt việc UISetting từ String sang Decimal 
         chỉ cần thay thế ký tự phân cách hàng nghìn thành ký tự trắng. ký tự phân cách thập phân không quan tâm
        */
        //sValue = sValue.Replace(Program.GroupSeparator, "");
        NumberFormatInfo numFormat = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat;
        //
        sValue = sValue.Replace(numFormat.NumberGroupSeparator, "");

        if (!Decimal.TryParse(sValue, out retVal))
            retVal = 0;
        return retVal;
    }

    public static Double ToDouble(object obj)
    {
        string sValue = "";
        if (obj != null)
            sValue = obj.ToString();

        Double retVal = 0;

        /*Hàm Decimal.TryParse thực hiện dựa theo CurrentCulture của chương trình.
        --> Để có thể sử dụng được tốt việc UISetting từ String sang Decimal 
         chỉ cần thay thế ký tự phân cách hàng nghìn thành ký tự trắng. ký tự phân cách thập phân không quan tâm
        */
        //sValue = sValue.Replace(Program.GroupSeparator, "");
        NumberFormatInfo numFormat = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat;
        //
        sValue = sValue.Replace(numFormat.NumberGroupSeparator, "");

        if (!Double.TryParse(sValue, out retVal))
            retVal = 0;
        return retVal;
    }

    public static DateTime ToDateTime(object obj)
    {
        string sValue = "";
        if (obj != null)
            sValue = obj.ToString();
        sValue = sValue.Trim();

        System.DateTime outDate = DateTime.MinValue;

        if (System.DateTime.TryParseExact(sValue, "dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out outDate))
        {
            return outDate;
        }
        else if (System.DateTime.TryParseExact(sValue, "MM/dd/yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out outDate))
        {
            return outDate;
        }
        else if (DateTime.TryParseExact(sValue, "d/M/yyyy", null, DateTimeStyles.None, out outDate))
        {
            return outDate;
        }
        else if (DateTime.TryParseExact(sValue, "dd/MM/yy", null, DateTimeStyles.None, out outDate))
        {
            return outDate;
        }
        else if (DateTime.TryParseExact(sValue, "MMM dd yyyy", null, DateTimeStyles.None, out outDate))
        {
            return outDate;
        }
        else if (DateTime.TryParseExact(sValue, "MMM dd yyyy HH:mmtt", null, DateTimeStyles.None, out outDate))
        {
            return outDate;
        }

        else if (DateTime.TryParseExact(sValue, "d-MM-yyyy", null, DateTimeStyles.None, out outDate))
        {
            return outDate;
        }

        else if (DateTime.TryParseExact(sValue, "dd-MM-yyyy", null, DateTimeStyles.None, out outDate))
        {
            return outDate;
        }
        else if (DateTime.TryParseExact(sValue, "d/M/yyyy", null, DateTimeStyles.None, out outDate))
        {
            return outDate;
        }
        else if (DateTime.TryParseExact(sValue, "yyyy'-'MM'-'dd'T'HH':'mm':'ss", null, DateTimeStyles.None, out outDate))
        {
            return outDate;
        }
        else if (System.DateTime.TryParse(sValue, out outDate))
        {
            return outDate;
        }
        else
        {
            return DateTime.MinValue;
        }
    }

    public static string convertToUnSign(string s)
    {
        Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
        string temp = s.Normalize(NormalizationForm.FormD);
        return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
    }

    public static void SendMail(string ToEmail, string[] _CCEmails, string Subject, string Comments, string UserComment)
    {
        //Configuration c = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
        //MailSettingsSectionGroup settings = (MailSettingsSectionGroup)c.GetSectionGroup("system.net/mailSettings");
        MailMessage mail = new MailMessage();
        SmtpClient smtp = new SmtpClient();
        //mail.From = new MailAddress(settings.Smtp.From.ToString());
        mail.From = new MailAddress("ibms.gic@gmail.com");
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        //smtp.EnableSsl = true;
        //smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        smtp.Credentials = new NetworkCredential("ibms.gic@gmail.com", "admin@gic");
        smtp.Timeout = 20000;


        mail.To.Add(new MailAddress(ToEmail));
        //CC cho nhiều địa chỉ Email
        for (int i = 0; i < _CCEmails.Length; i++)
        {
            if (_CCEmails[i].ToString() != "")
                mail.CC.Add(new MailAddress(_CCEmails[i]));
        }
        mail.Subject = Subject;
        mail.SubjectEncoding = System.Text.Encoding.UTF8;
        mail.Body = Comments + "<br />" +
            "<br />-------------------------------" +
            "<br />Người gửi: " + UserComment +
            "<br />-------------------------------";
        mail.IsBodyHtml = true;
        //
        object userState = mail;
        smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
        smtp.EnableSsl = true;
        smtp.SendAsync(mail, userState);

    }

    static void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
    {
        //Get the Original MailMessage object
        //MailMessage mail = (MailMessage)e.UserState;

        //write out the subject
        //string subject = mail.Subject;

        //if (e.Cancelled)
        //{
        //    Console.WriteLine("Send canceled for mail with subject [{0}].", subject);
        //}
        //if (e.Error != null)
        //{
        //    Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString());
        //}
        //else
        //{
        //    Console.WriteLine("Message [{0}] sent.", subject);
        //}           
    }

    public static List<T> ToList<T>(ArrayList arrayList)
    {
        List<T> list = new List<T>(arrayList.Count);
        foreach (T instance in arrayList)
        {
            list.Add(instance);
        }
        return list;
    }

    public static object GetPreperty(object o, string name)
    {
        PropertyInfo pi = o.GetType().GetProperty(name);
        if (pi != null)
        {
            return pi.GetValue(o, null);
        }
        return null;
    }

    public static List<T> ConvertArrayToList<T>(ArrayList arrayList)
    {
        List<T> list = new List<T>(arrayList.Count);
        foreach (T instance in arrayList)
        {
            list.Add(instance);
        }
        return list;
    }

    public static void setFolderPermission(string path)
    {
        DirectorySecurity sec = Directory.GetAccessControl(path);
        // Using this instead of the "Everyone" string means we work on non-English systems.
        SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

        //sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
        sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));

        Directory.SetAccessControl(path, sec);

    }

    public static bool IsDateTime(object obj, string format)
    {
        string sValue = "";
        if (obj == null || obj == DBNull.Value)
            sValue = "";
        else
            sValue = obj.ToString();
        DateTime dateVal;
        return DateTime.TryParseExact(sValue, format, null, System.Globalization.DateTimeStyles.None, out  dateVal);
    }

    public static bool IsDateTime(object obj, string format, out DateTime returnValue)
    {
        string sValue = "";
        if (obj == null || obj == DBNull.Value)
            sValue = "";
        else
            sValue = obj.ToString();

        returnValue = DateTime.MinValue;
        return DateTime.TryParseExact(sValue, format, null, System.Globalization.DateTimeStyles.None, out  returnValue);
    }

    public static bool IsEmpty(object obj)
    {
        string sValue = "";
        if (obj == null || obj == DBNull.Value)
            sValue = "";
        else
            sValue = obj.ToString();
        return (sValue.Trim().Length == 0);
    }
    
    public static bool IsNumeric(object obj)
    {
        string sValue = "";
        if (obj == null || obj == DBNull.Value)
            sValue = "";
        else
            sValue = obj.ToString();

        Decimal DecVal = 0;
        return Decimal.TryParse(sValue, out DecVal);
    }
    
    public static bool IsInteger(object obj)
    {
        string sValue = "";
        if (obj == null || obj == DBNull.Value)
            sValue = "";
        else
            sValue = obj.ToString();
        int intVal = 0;
        return Int32.TryParse(sValue, out intVal);
    }
    
    public static bool IsValidPhoneNumber(object obj)
    {
        string sValue = "";
        if (obj == null || obj == DBNull.Value)
            sValue = "";
        else
            sValue = obj.ToString();

        if (sValue.Length > 7 && sValue.Length < 16)
        {
            for (int i = 0; i < sValue.Length; i++)
                if (!Char.IsDigit(sValue[i]))
                    return false;
            return true;
        }
        return false;
    }
    
    public static bool IsValidEmail(object obj)
    {
        string sValue = "";
        if (obj == null || obj == DBNull.Value)
            sValue = "";
        else
            sValue = obj.ToString();

        string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                              + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                              + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                              + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                              + @"[a-zA-Z]{2,}))$";

        Regex reStrict = new Regex(patternStrict);

        return reStrict.IsMatch(sValue);
    }
    
    public static bool IsDBNull(object obj)
    {
        if (obj == null || obj == DBNull.Value)
            return true;
        else
            return false;
    }

    public static string GetProcessorId()
    {
        string strProcessorId = string.Empty;
        SelectQuery query = new SelectQuery("Win32_processor");
        ManagementObjectSearcher search = new ManagementObjectSearcher(query);

        foreach (ManagementObject info in search.Get())
        {
            strProcessorId = info["processorId"].ToString();
        }

        return strProcessorId;
    }

    public static string GetMotherBoardID()
    {
        string strMotherBoardID = string.Empty;
        SelectQuery query = new SelectQuery("Win32_BaseBoard");
        ManagementObjectSearcher search = new ManagementObjectSearcher(query);

        foreach (ManagementObject info in search.Get())
        {
            strMotherBoardID = info["SerialNumber"].ToString();
        }

        return strMotherBoardID;
    }

    public static string GetMACAddress()
    {
        ManagementScope theScope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
        StringBuilder theQueryBuilder = new StringBuilder();
        theQueryBuilder.Append("SELECT MACAddress FROM Win32_NetworkAdapter");
        ObjectQuery theQuery = new ObjectQuery(theQueryBuilder.ToString());
        ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
        ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

        string macAdd = "";
        foreach (ManagementObject theCurrentObject in theCollectionOfResults)
        {
            if (theCurrentObject["MACAddress"] != null)
                macAdd += theCurrentObject["MACAddress"].ToString();
        }

        return macAdd;
    }
}
